package com.example.randomthoughts.daimasuixianglu.inputAndooutput;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * @author csd
 * @version 1.0
 * 二叉树的输入输出练习
 */
@SuppressWarnings({"all"})
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    public TreeNode(int val) {
        this.val = val;
    }
}

public class binary_tree {
    //首先事传入一个字符串数组
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] strings = in.nextLine().split(",");
        int[] intArray = Arrays.stream(strings)
                .mapToInt(Integer::parseInt)
                .toArray();
        TreeNode root = buildTree(intArray);
        firstTraversal(root);
    }

    public static TreeNode buildTree(int[] num) {
        List<TreeNode> treeNodeList = num.length > 0 ? new ArrayList<>(num.length) : null;
        TreeNode root = null;
        for (int i = 0; i < num.length; i++) {
            TreeNode node = null;
            if (num[i] != -1) {
                node = new TreeNode(num[i]);
            }
            treeNodeList.add(node);
            if (i == 0) {
                root = node;
            }
        }
        for (int i = 0; i * 2 + 1 < num.length; i++) {
            TreeNode node = treeNodeList.get(i);
            if (node != null) {
                node.left = treeNodeList.get(i * 2 + 1);
                if (i * 2 + 2 < num.length)
                    node.right = treeNodeList.get(i * 2 + 2);
            }
        }
        return root;
    }

    public static void firstTraversal(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.println(root.val);
        firstTraversal(root.left);
        firstTraversal(root.right);
    }

}
